<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Route,URL,Auth;

class AuthenticateAdmin
{

    public function handle($request, Closure $next)
    {
        if(Auth::guard('admin')->user()->id === 1 || Auth::guard('admin')->user()->dengji === 1 || Auth::guard('admin')->user()->dengji === 2 || Auth::guard('admin')->user()->dengji === 3){
            return $next($request);
        }

        $current_action = $this->getCurrentAction();

        //$current_url = str_replace('public/','',strstr($_SERVER['REQUEST_URI'],'public/'));
        //$current_permission_id = db::table('permissions')->where('rule','LIKE',$current_url)->value('id');
        //获取当前访问的控制器方法对应的权限id
        $current_permission_id = db::table('permissions')->where('path',$current_action)->value('id');
        //查询用户拥有的权限
        $permission = db::table('roles')->where('id',Auth::user()->role_id)->value('permission_id');
        $array = explode(",",$permission);

        if(!in_array($current_permission_id,$array)){
            if($request->ajax() && ($request->getMethod() != 'GET')) {
                return response()->json([
                    'status' => -1,
                    'code' => 403,
                    'msg' => '您没有权限执行此操作'
                ]);
            } else {
                $previousUrl = URL::previous();
                return response()->view('admin.errors.403', compact('previousUrl'));
            }
        }

        return $next($request);
    }

    /**
     * 获取当前控制器名
     *
     * @return string
     */
    public function getCurrentControllerName()
    {
        return $this->getCurrentAction()['controller'];
    }

    /**
     * 获取当前方法名
     *
     * @return string
     */
    public function getCurrentMethodName()
    {
        return $this->getCurrentAction()['method'];
    }

    /**
     * 获取当前控制器与方法
     *
     * @return array
     */
    public function getCurrentAction()
    {
        $action = \Route::current()->getActionName();
        //dd($action);
        //list($class, $method) = explode('@', $action);
        //return ['controller' => $class, 'method' => $method];
        return $action;
    }
}
